import { Injectable } from '@nestjs/common';
import { qn_upload } from 'src/common/configs/qiniuyun';
import { Response } from 'src/utils/response';
import { PassThrough } from 'node:stream';

@Injectable()
export class UploadService {
  constructor() {}

  uploadFile(file: Express.Multer.File) {
    return new Promise((resolve) => {
      const { originalname, buffer } = file;
      // 生成文件名
      const key = `${new Date().getTime()}-${originalname}`;
      // 创建PassThrough流并写入Buffer
      const readStream = new PassThrough();
      readStream.end(buffer);
      try {
        qn_upload(key, readStream).then((resp) => {
          resolve(
            Response.success({
              data: {
                url: `http://file.zyhccflame.top/${resp.key}`,
              },
            }),
          );
        });
      } catch (error) {
        resolve(Response.error({ message: '上传失败' + error }));
      }
    });
  }
}
